package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.messageprocessors.RequestProcessorImp;

import java.util.Date;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.AddressType;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.msg.ExceptionResponse;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ModbusUtil;
import net.wimpi.modbus.msg.WriteMultipleRegistersRequest;
import net.wimpi.modbus.msg.WriteMultipleRegistersResponse;
import net.wimpi.modbus.procimg.IllegalAddressException;
import net.wimpi.modbus.procimg.Register;

public class WriteMultipleRegistersRequestProcessor extends
		AbstractRequestProcessor {

	@Override
	public ModbusResponse processRequest(ModbusRequest req) {
		
		ModbusResponse res;
		//TODO: chequear limites del protocolo
		Register[] regs = ((WriteMultipleRegistersRequest) req).getRegisters();
		int baseDir = ((WriteMultipleRegistersRequest) req).getReference();
		Date date = new Date();

		res = new WriteMultipleRegistersResponse(baseDir, regs.length);
		
		try {
			
			for(int i = 0; i < regs.length; i++){
				
				int address = baseDir + i;
				Register value = regs[i];
				
				getImage().setRegister(address,value,date);
				
				if( getDeciveDAO() != null )
						getDeciveDAO().saveValue( getDevice(), address , value.getValue() , AddressType.HOLDING_REGISTER );
			}
			
			ModbusUtil.setFunctionCode(res, Modbus.WRITE_MULTIPLE_REGISTERS);
		}
		catch(IllegalAddressException e){
			res = new ExceptionResponse(req.getFunctionCode(), 2);
		}
		
		ModbusUtil.setMessageData(res,req);
		
		return res;
	}

}
